/**
 * 历史记录页面事件处理器
 * 负责处理历史记录页面相关的所有事件和逻辑
 */
class HistoryHandler {
    constructor(appState, apiService, uiUtils) {
        this.appState = appState;
        this.apiService = apiService;
        this.uiUtils = uiUtils;
    }

    /**
     * 初始化历史记录页面
     */
    async init() {
        console.log('[HistoryHandler] 初始化历史记录页面');
        
        // 加载工作区列表（会自动绑定事件）
        await this.loadWorkspaceList();
    }

    /**
     * 加载工作区列表（项目列表）
     */
    async loadWorkspaceList() {
        console.log('[HistoryHandler] 加载工作区列表');
        
        try {
            if (!window.electronAPI || !window.electronAPI.getWorkspaceListWithStats) {
                console.warn('[HistoryHandler] 历史API不可用');
                return;
            }

            const result = await window.electronAPI.getWorkspaceListWithStats();
            
            if (result.success && result.workspaces.length > 0) {
                console.log('[HistoryHandler] 加载了', result.workspaces.length, '个工作区');
                this.renderWorkspaceList(result.workspaces);
            } else {
                console.log('[HistoryHandler] 暂无项目记录');
                this.renderWorkspaceList([]);
            }
        } catch (error) {
            console.error('[HistoryHandler] 加载工作区列表失败:', error);
        }
    }

    /**
     * 渲染工作区列表（项目列表）
     * @param {Array} workspaces - 工作区列表
     */
    renderWorkspaceList(workspaces) {
        const historyContainer = document.querySelector('#history .history-list');
        if (!historyContainer) {
            console.warn('[HistoryHandler] 未找到历史列表容器');
            return;
        }

        if (!workspaces || workspaces.length === 0) {
            historyContainer.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-folder-open"></i>
                    <p>暂无项目记录</p>
                </div>
            `;
            return;
        }

        const workspaceHTML = workspaces.map(workspace => {
            const lastAccessTime = new Date(workspace.lastAccess).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            const lastTaskStatus = workspace.lastTask ? workspace.lastTask.status : 'unknown';
            const statusClass = lastTaskStatus === 'success' ? 'success' : 'error';
            const lastTaskTitle = workspace.lastTask ? (workspace.lastTask.title || workspace.lastTask.task) : '无对话';

            return `
                <div class="workspace-item" data-path="${this.escapeHtml(workspace.path)}">
                    <div class="workspace-item-header">
                        <div class="workspace-icon">
                            <i class="fas fa-folder-open"></i>
                        </div>
                        <div class="workspace-info">
                            <h4 class="workspace-name">${this.escapeHtml(workspace.displayName)}</h4>
                            <p class="workspace-path">${this.escapeHtml(workspace.path)}</p>
                        </div>
                    </div>
                    <div class="workspace-meta">
                        <span class="workspace-task-count">
                            <i class="fas fa-comments"></i>
                            ${workspace.taskCount} 次对话
                        </span>
                        <span class="workspace-last-access">
                            <i class="fas fa-clock"></i>
                            ${lastAccessTime}
                        </span>
                    </div>
                    <div class="workspace-last-task">
                        <span class="last-task-label">最近对话：</span>
                        <span class="last-task-title ${statusClass}">${this.escapeHtml(lastTaskTitle)}</span>
                    </div>
                    <div class="workspace-actions">
                        <button class="btn-open-workspace">
                            <i class="fas fa-arrow-right"></i>
                            打开项目
                        </button>
                        <button class="btn-open-folder">
                            <i class="fas fa-external-link-alt"></i>
                            打开文件夹
                        </button>
                    </div>
                </div>
            `;
        }).join('');

        historyContainer.innerHTML = workspaceHTML;
        
        console.log('[HistoryHandler] HTML 已渲染，容器内容:');
        console.log(historyContainer.innerHTML.substring(0, 500));
        
        // 检查按钮是否存在
        const allButtons = historyContainer.querySelectorAll('button');
        console.log('[HistoryHandler] 找到', allButtons.length, '个按钮');
        allButtons.forEach((btn, i) => {
            console.log(`按钮 ${i + 1}: class="${btn.className}", text="${btn.textContent.trim()}"`);
        });
        
        // 渲染完成后立即绑定事件
        this.setupHistoryPageEvents();
    }

    /**
     * 获取路径的基础名称
     */
    getPathBasename(fullPath) {
        if (!fullPath) return '未知';
        const parts = fullPath.split('/');
        return parts[parts.length - 1] || parts[parts.length - 2] || '未知';
    }

    /**
     * 转义HTML
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * 设置历史记录页面事件（使用事件委托）
     */
    setupHistoryPageEvents() {
        console.log('[HistoryHandler] 设置历史记录页面事件');
        
        const historyContainer = document.querySelector('#history .history-list');
        if (!historyContainer) {
            console.warn('[HistoryHandler] 未找到历史列表容器');
            return;
        }
        
        console.log('[HistoryHandler] 使用事件委托绑定按钮事件');
        
        // 使用事件委托处理所有按钮点击
        historyContainer.addEventListener('click', (e) => {
            // 查找最近的按钮元素（从点击目标向上查找）
            const button = e.target.closest('button');
            
            console.log('[HistoryHandler] 点击事件 - 目标:', e.target.tagName, '按钮:', button);
            
            if (!button) {
                console.log('[HistoryHandler] 不是按钮点击');
                return;
            }
            
            // 阻止默认行为和事件冒泡
            e.preventDefault();
            e.stopPropagation();
            
            console.log('[HistoryHandler] 找到按钮，class:', button.className);
            
            // 查找最近的工作区项目
            const workspaceItem = button.closest('.workspace-item');
            if (!workspaceItem) {
                console.warn('[HistoryHandler] 未找到工作区项目');
                return;
            }
            
            const workPath = workspaceItem.getAttribute('data-path');
            console.log('[HistoryHandler] 工作路径:', workPath);
            
            // 判断是哪个按钮
            if (button.classList.contains('btn-open-workspace')) {
                console.log('[HistoryHandler] ✅ 点击了"打开项目"按钮');
                this.handleOpenWorkspace(workPath);
            } else if (button.classList.contains('btn-open-folder')) {
                console.log('[HistoryHandler] ✅ 点击了"打开文件夹"按钮');
                this.handleOpenFolder(workPath);
            } else {
                console.warn('[HistoryHandler] 未知的按钮类型:', button.className);
            }
        });
        
        console.log('[HistoryHandler] 事件委托已设置完成');
    }

    /**
     * 处理打开工作区（项目）
     * @param {string} workPath - 工作路径
     */
    async handleOpenWorkspace(workPath) {
        console.log('[HistoryHandler] 打开工作区:', workPath);
        
        // 跳转到任务页面
        if (window.switchTab) {
            window.switchTab('tasks');
        }
        
        // 等待页面加载
        setTimeout(() => {
            // 通知任务页面加载该工作区
            if (window.tasksHandler && window.tasksHandler.loadWorkspace) {
                window.tasksHandler.loadWorkspace(workPath);
            }
        }, 100);
    }

    /**
     * 处理打开文件夹
     * @param {string} workPath - 工作路径
     */
    async handleOpenFolder(workPath) {
        console.log('[HistoryHandler] 打开文件夹:', workPath);
        
        try {
            const result = await window.electronAPI.openFolderLocation(workPath);
            if (result.success) {
                console.log('[HistoryHandler] 文件夹已在系统文件管理器中打开');
            } else {
                console.error('[HistoryHandler] 打开文件夹失败:', result.error);
                alert(`打开文件夹失败: ${result.error}`);
            }
        } catch (error) {
            console.error('[HistoryHandler] 打开文件夹异常:', error);
            alert(`打开文件夹异常: ${error.message}`);
        }
    }
}

// 确保 HistoryHandler 在全局作用域可用
if (typeof window !== 'undefined') {
    window.HistoryHandler = HistoryHandler;
}